import { Button, Cell,  DatePicker, Input, Radio, Toast } from "@nutui/nutui-react-taro";
import { Form } from "@nutui/nutui-react-taro";
import { PickerOption } from "@nutui/nutui-react-taro/dist/types/packages/picker/types";

import Taro, { useShareAppMessage } from "@tarojs/taro";
import {
  changeMember_id,
  changeOpenid,
  changeUser,
  phoneOpenid,
  storeMember_id,
  storeUser,
} from "@/redux/userSlice";
import { View } from "@tarojs/components";

import { useEffect,  useState } from "react";
import { useDispatch, useSelector } from "react-redux";

import { ApiCheckLogin, ApiLogout, ApiMemberInfo, ApiMemberUpdate } from "../../utils/api";

import "../../app.scss";

import dayjs from "dayjs";


const infoChange = () => {
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进会员",
      path: "pages/home/index", //?id=123
      // imageUrl,
      imageUrl: "../../assets/home.jpg",
    };
  });
  const dispatch = useDispatch();
  // 导入仓库 2.使用属性
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);
  // const storeMemberId = useSelector(storeMember_id);

  // 表单控件
  const [form] = Form.useForm();

  // loadding
  const [loading, setLoading] = useState(true);

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);
  const [registerForm, SetRegisterForm] = useState({
    openid: Taro.getStorageSync("openid") || "",
    sessionKey: Taro.getStorageSync("sessionKey") || "",
  });
  const [wxLoginForm, setWxLoginForm] = useState({
    code: "",
    encryptedIv: "",
    encryptedData: "",
  });

  // 日期
  const [show1, setShow1] = useState(false);
  const [desc1, setDesc1] = useState("请选择日期");
  const confirm1 = (values: (string | number)[], options: PickerOption[]) => {
    // console.log(options, "options");
    setDesc1(options.map((option) => option.value).join("-"));
    // setDesc1(options.map((option) => option.text).join(" "));
    // console.log(options.map((option) => option.value).join("-"));
    // console.log(dayjs(options.map((option) => option.text).join(" ")).format("YYYY-MM-DD"));
  };

  const noOpenId = () => {
    // Taro.getSetting：获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
    Taro.getSetting({
      success: async (res) => {
        if (res.authSetting["scope.userInfo"]) {
          // 用户已经授权过，可以直接获取用户信息
          getUserInfo();
          getopenId();
        } else {
          // 用户未授权，需要弹出授权窗口
          showAuthModal();
        }
      },
    });
  };
  // 授权窗口
  const showAuthModal = () => {
    Taro.showModal({
      title: "授权提示",
      content: "需要获取您的用户信息",
      confirmText: "去授权",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，打开授权设置页面
          openSetting();
        }
      },
    });
  };
  const openSetting = () => {
    // Taro.openSetting：调起客户端小程序设置界面，返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。
    Taro.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"]) {
          // 用户授权成功，可以获取用户信息
          getUserInfo();
        } else {
          // 用户拒绝授权，提示授权失败
          Taro.showToast({
            title: "授权失败",
            icon: "none",
          });
        }
      },
    });
  };
  const getUserInfo = () => {
    Taro.getUserInfo({
      success: async (res) => {
        const { encryptedData, iv } = res;
        // console.log(encryptedData, "encryptedData");
        // console.log(iv, "iv");
        console.log(res.userInfo, "res.userInfo");
        // setUserInfo(registerForm.openid);
        // 渲染用户信息
        // deterName(res.userInfo);
        await checkLogin()
        getMemberInfo()
        // 在这里将 encryptedData 和 iv 传给后端解密获取用户信息
        const myWxLoginForm = {
          ...wxLoginForm,
          encryptedIv: iv,
          encryptedData: encryptedData,
        };
        setWxLoginForm(myWxLoginForm);
        // getPhoneNumber(myWxLoginForm);
      },
    });
  };

  // 获取openid
  const getopenId = () => {
    console.log(1);
    Taro.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          // const appid = "wxa18cf1d233575f8c";
          // const sec = "38c61bd84a0403baeabe1e0e6a7024f7";

          //https: api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&sec=APPSE

          const url =
            "https://api.weixin.qq.com/sns/jscode2session?appid=wxa18cf1d233575f8c&sec=38c61bd84a0403baeabe1e0e6a7024f7&grant_type=authorization_code&js_code=" +
            res.code;
          Taro.request({
            // url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wxea9e81628b4a19c6&sec=e96f9c56ede2efb9ecd3c8d4e00913aa&grant_type=authorization_code&js_code=+res.code}',
            // url: "https://api.weixin.qq.com/sns/jscode2session",
            url,
            // data: {
            //   grant_type: "authorization_code",
            //   js_code: res.code,
            //   appid,
            //   sec,
            // },
            success: (res) => {
              console.log(res.data, "data");
              // that.registerForm = {
              // 	...that.registerForm,
              // 	openid: res.data.openid,
              // 	sessionKey: res.data.sessionKey
              // }
              const myRegisterForm = {
                ...registerForm,
                openid: res.data.openid,
                sessionKey: res.data.session_key,
              };
              SetRegisterForm(myRegisterForm);
              // handleGetPhoneNumber(myRegisterForm);
              // registerForm.openid = res.data.openid;
              // registerForm.sessionKey = res.data.session_key;
              console.log(myRegisterForm, "myRegisterForm");
              // Taro.setStorageSync("openid", res.data.openid);
              // handleUserTokenEncryption("openid", {
              //   openid: res.data.openid,
              // });
              //     // 移除旧的存储
              //     Taro.removeStorage({ key: name });

              //     // 存储新的加密令牌
              Taro.setStorageSync("openid", res.data.openid);
              Taro.setStorageSync("sessionKey", res.data.session_key);
              // 存到仓库
              dispatch(changeOpenid(res.data.openid));
              console.log(111);
              // $modal.closeLoading();
            },
          });
        } else {
          console.log("登录失败！" + res.errMsg);
          // this.$modal.closeLoading()
        }
      },
    });
  };

  const [state, SetState] = useState({
    msg: "toast",
    type: "text",
    cover: false,
    duration: 2,
    closeOnOverlayClick: false,
    icon: "",
    center: true,
  });
  const [showToast, SetShowToast] = useState(false);

  // 用户手机号等
  const [formData, setFormData] = useState({
    name: "",
    sex: -1,
    birthday: "",
    mobile: "",
    captcha: "",
    plate_number: "",
  });

  // 用于修改更新用户
  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log("value", value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };
  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // console.log("formData", formData);
  };


  // 修改信息
  const determine = async () => {
    // 校验是否有openid和session_member_id
    if (!myOpenid || !member_id) {
      console.log("没有获取openid或没有校验登录");
      noOpenId()
      return;
    }
    // 格式化日期
    let myFormData = formData;
    if (formData.birthday) {
      myFormData = {
        ...formData,
        birthday: dayjs(formData.birthday).format("YYYY-MM-DD") as any,
      };
      console.log(myFormData, "myFormData");
    }
    // 请求参数
    const params = {
      ...myFormData,
      openid: myOpenid,
      session_member_id: member_id,
      birthday: desc1,
    };
    console.log(params, "params");
    // 请求修改信息
    let res 
    try {
      res = await ApiMemberUpdate(params);
      // 请求成功
      if (res.code == 0) {
        //  存到仓库
        dispatch(changeUser({ ...formData, birthday: desc1 }));
        setFormData({ ...formData, birthday: desc1 });
        // Toast.show("test", { title: "保存成功", duration: 2, type: "success" });
        Taro.showToast({
          title: "保存成功",
          duration: 2000,
          icon: "success",
        });
        // 修改登录状态
        console.log(res.data, "修改成功");
        setTimeout(()=>{
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        },700)
      } else {
        Toast.show("test", { title: "保存失败", duration: 2, type: "fail" });
      }
    } catch (error) {
      if (error.code == 2001) {
        Toast.show("test", { title: error.msg, duration: 2, type: "fail" });
      } else {
        Toast.show("test", { title: error.msg, duration: 2, type: "fail" });
      }
    }

  };


  // 请求登录状态
    const checkLogin = async () => {
      if (!myOpenid) {
        // 去到注册页
        Taro.reLaunch({
          url: "/pages/home/index",
        });
      }
      console.log(myOpenid, "openid");
      // console.log(formData, "formData");
      // 暂时先用手机号+
      const res = await ApiCheckLogin(myOpenid);
      if (res.code == 0) {
        // 当前页面使用
        setMember_id(res.data.member_id);
        // await getMemberInfo(res.data.member_id);
        // 用于后续 获取会员详情信息
        console.log(res.data.member_id);
        await getMemberInfo(res.data.member_id);
        return res.data.member_id;
      } else if (res.code == 2001) {
        await ApiLogout();
        await checkLogin();
        console.warn("ApiCheckLogin失败");
        Taro.showToast({
          title: res.msg || "失败",
          icon: "error",
        });
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        }, 500);
      } else {
        console.warn("未登录");
        Taro.showToast({
          title: res.msg || "失败",
          icon: "error",
        });
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        }, 500);
        return;
      }
    };
  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    console.log(my_member_id, "my_member_id");
    if (!myOpenid) {
      console.log("需重新进入");
      return;
    }
    console.log(myOpenid, "myOpenid");
    // 请求用户信息

    // 校验是否有
    let resInfo;
    // console.log(user, "user");
    if (!user.mobile) {
      try {
        resInfo = await ApiMemberInfo(my_member_id);
      } finally {
        // 无论请求成功或失败，都设置 loading 为 false
        // 使用骨架屏
        setLoading(false);
      }
      // console.log(resInfo, "resInfo");
      if (resInfo.code != 0) {
        console.log("请求用户信息失败");
        return;
      } else {
        // setIsMember(1);
      }
      // 没有请求,存仓库
      dispatch(changeUser(resInfo.data));
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = resInfo.data;
      // 更新
      handleNameInputChange("name", name);
      handleNameInputChange("mobile", mobile);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "未绑定"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      // handleNameInputChange("birthday", new Date(birthday));
      setDesc1(birthday);
    } else {
      setLoading(false);
      // 从仓库读取
      // console.log(user, "user");
      // 更新用户对象
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = user;
      handleNameInputChange("name", name);
      handleNameInputChange("mobile", mobile);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "未绑定"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      // handleNameInputChange("birthday", new Date(birthday));
      setDesc1(birthday);
    }
    // form.setFieldsValue(formData);
    return resInfo;
  };

  useEffect(() => {
    getMemberInfo();
  }, []);

  // 更新界面
  // 挂载页面
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [formData, form]);

  return (
    <View>
      <Toast id="test" />
      <Toast
        msg={state.msg}
        visible={showToast}
        type={state.type}
        onClose={() => {
          SetShowToast(false);
        }}
      />

      <Form
        style={{ display: loading ? "none" : "block" }}
        initialValues={{ ...formData }}
        // onFinish={onFinish}
        divider
        labelPosition="top"
        form={form}
        footer={
          <Button
            formType="submit"
            style={{
              backgroundColor: "#1677ff",
              border: "hsl(215, 100%, 84%)",
              width: "90vw",
              paddingTop: "3.3vh",
              paddingBottom: "3.3vh",
              fontSize: "4.8vw",
            }}
            block
            color="primary"
            size="large"
            onClick={determine}
          >
            确认
          </Button>
        }
      >
        <Form.Item label="姓名" name="name">
          <Input
            placeholder="请输入姓名"
            onChange={(value) => handleNameInputChange("name", value)}
          />
        </Form.Item>
        <Form.Item label="性别" name="sex">
          <Radio.Group
            direction="horizontal"
            onChange={(value) => handleNameInputChange("sex", value)}
          >
            <Radio value={1}>男</Radio>
            <Radio value={2}>女</Radio>
          </Radio.Group>
        </Form.Item>
        <>
          <Cell
            title="出生日期"
            description={<>{desc1 ? desc1 : "请选择日期"}</>}
            onClick={() => setShow1(true)}
          />
          <DatePicker
            startDate={new Date("1950")}
            endDate={new Date()}
            title="日期选择"
            visible={show1}
            showChinese
            onClose={() => setShow1(false)}
            onConfirm={(options, values) => confirm1(values, options)}
          />
        </>
      </Form>
    </View>
  );
};

export default infoChange;
